<template>
  <div class="chat-container" :class="containerClass">
    <!-- 聊天头部 -->
    <div v-if="showHeader" class="chat-header" :class="headerClass">
      <div class="chat-header-left">
        <!-- 当前人格信息 -->
        <div v-if="currentPersona" class="chat-persona-info">
          <div class="chat-persona-avatar">
            <img
              v-if="currentPersona.avatar"
              :src="currentPersona.avatar"
              :alt="currentPersona.name"
              class="persona-avatar-image"
            />
            <Icon v-else name="user" :size="32" class="persona-avatar-icon" />
          </div>

          <div class="chat-persona-details">
            <h3 class="persona-name">{{ currentPersona.name }}</h3>
            <p class="persona-description">{{ currentPersona.description }}</p>
          </div>
        </div>
      </div>

      <div class="chat-header-right">
        <slot name="header-actions"></slot>

        <!-- 聊天设置 -->
        <Button
          type="secondary"
          variant="text"
          icon="settings"
          @click="showSettings = true"
        >
          设置
        </Button>

        <!-- 清空聊天 -->
        <Button
          type="secondary"
          variant="text"
          icon="trash"
          @click="handleClearChat"
        >
          清空
        </Button>
      </div>
    </div>

    <!-- 聊天消息区域 -->
    <div class="chat-messages" :class="messagesClass" ref="messagesRef">
      <!-- 欢迎消息 -->
      <div v-if="showWelcome && messages.length === 0" class="chat-welcome">
        <div class="welcome-content">
          <Icon name="message-circle" :size="48" class="welcome-icon" />
          <h3 class="welcome-title">开始对话</h3>
          <p class="welcome-description">{{ welcomeText }}</p>

          <!-- 快捷问题 -->
          <div v-if="quickQuestions.length > 0" class="quick-questions">
            <Button
              v-for="question in quickQuestions"
              :key="question"
              type="secondary"
              variant="outlined"
              size="small"
              @click="handleQuickQuestion(question)"
            >
              {{ question }}
            </Button>
          </div>
        </div>
      </div>

      <!-- 消息列表 -->
      <div v-else class="messages-list">
        <ChatMessage
          v-for="message in messages"
          :key="message.id"
          :message="message"
          :current-persona="currentPersona"
          :show-avatar="showMessageAvatar"
          :show-time="showMessageTime"
          @retry="handleRetry"
          @copy="handleCopy"
          @delete="handleDeleteMessage"
        />

        <!-- 正在输入指示器 -->
        <div v-if="isTyping" class="typing-indicator">
          <div class="typing-avatar">
            <img
              v-if="currentPersona?.avatar"
              :src="currentPersona.avatar"
              :alt="currentPersona.name"
              class="typing-avatar-image"
            />
            <Icon v-else name="user" :size="24" class="typing-avatar-icon" />
          </div>

          <div class="typing-content">
            <div class="typing-dots">
              <div class="dot"></div>
              <div class="dot"></div>
              <div class="dot"></div>
            </div>
            <span class="typing-text"
              >{{ currentPersona?.name || "AI" }} 正在输入...</span
            >
          </div>
        </div>
      </div>

      <!-- 滚动到底部按钮 -->
      <Transition name="scroll-button">
        <Button
          v-if="showScrollButton"
          class="scroll-to-bottom"
          type="primary"
          variant="filled"
          icon="chevron-down"
          size="small"
          @click="scrollToBottom"
        >
          回到底部
        </Button>
      </Transition>
    </div>

    <!-- 聊天输入区域 -->
    <div class="chat-input-area" :class="inputAreaClass">
      <ChatInput
        v-model="inputText"
        :placeholder="inputPlaceholder"
        :disabled="disabled || isTyping"
        :loading="sending"
        :max-length="maxInputLength"
        :support-multimodal="supportMultimodal"
        @send="handleSend"
        @file-upload="handleFileUpload"
        @voice-input="handleVoiceInput"
      />
    </div>

    <!-- 聊天设置弹窗 -->
    <Modal v-model:visible="showSettings" title="聊天设置" size="medium">
      <ChatSettings
        v-model:settings="chatSettings"
        @save="handleSaveSettings"
      />
    </Modal>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, nextTick, onMounted, onUnmounted } from "vue";
import { useChatStore } from "@/stores/chat";
import { usePersonaStore } from "@/stores/persona";
import Icon from "@/components/common/Icon.vue";
import Button from "@/components/common/Button.vue";
import Modal from "@/components/common/Modal.vue";
import ChatMessage from "./ChatMessage.vue";
import ChatInput from "./ChatInput.vue";
import ChatSettings from "./ChatSettings.vue";

interface ChatMessage {
  id: string;
  type: "user" | "assistant" | "system";
  content: string;
  timestamp: number;
  status?: "sending" | "sent" | "failed";
  attachments?: any[];
  metadata?: Record<string, any>;
}

interface ChatSettings {
  autoScroll: boolean;
  showTimestamp: boolean;
  showAvatar: boolean;
  soundEnabled: boolean;
  theme: "light" | "dark" | "auto";
}

interface Props {
  // 基础属性
  sessionId?: string;

  // 样式
  height?: string | number;

  // 功能
  showHeader?: boolean;
  showWelcome?: boolean;
  showMessageAvatar?: boolean;
  showMessageTime?: boolean;
  supportMultimodal?: boolean;

  // 输入
  inputPlaceholder?: string;
  maxInputLength?: number;

  // 状态
  disabled?: boolean;

  // 欢迎信息
  welcomeText?: string;
  quickQuestions?: string[];

  // 类名
  containerClass?: string;
  headerClass?: string;
  messagesClass?: string;
  inputAreaClass?: string;
}

const props = withDefaults(defineProps<Props>(), {
  showHeader: true,
  showWelcome: true,
  showMessageAvatar: true,
  showMessageTime: true,
  supportMultimodal: true,
  inputPlaceholder: "输入消息...",
  maxInputLength: 2000,
  welcomeText: "你好！我是你的AI助手，有什么可以帮助你的吗？",
  quickQuestions: () => [
    "你好",
    "你能做什么？",
    "帮我写一首诗",
    "今天天气怎么样？",
  ],
});

const emit = defineEmits<{
  send: [message: string, attachments?: any[]];
  messageDelete: [messageId: string];
  settingsChange: [settings: ChatSettings];
  clearChat: [];
}>();

// Store
const chatStore = useChatStore();
const personaStore = usePersonaStore();

// 响应式数据
const messagesRef = ref<HTMLElement>();
const inputText = ref("");
const showSettings = ref(false);
const showScrollButton = ref(false);
const chatSettings = ref<ChatSettings>({
  autoScroll: true,
  showTimestamp: true,
  showAvatar: true,
  soundEnabled: false,
  theme: "auto",
});

// 计算属性
const messages = computed(() => {
  return chatStore.currentSession?.messages || [];
});

const currentPersona = computed(() => {
  return personaStore.currentPersona;
});

const isTyping = computed(() => {
  return chatStore.isTyping;
});

const sending = computed(() => {
  return chatStore.sending;
});

// 方法
const scrollToBottom = (smooth = true) => {
  if (!messagesRef.value) return;

  const scrollOptions: ScrollToOptions = {
    top: messagesRef.value.scrollHeight,
    behavior: smooth ? "smooth" : "auto",
  };

  messagesRef.value.scrollTo(scrollOptions);
};

const checkScrollButton = () => {
  if (!messagesRef.value) return;

  const { scrollTop, scrollHeight, clientHeight } = messagesRef.value;
  const isNearBottom = scrollHeight - scrollTop - clientHeight < 100;

  showScrollButton.value = !isNearBottom && messages.value.length > 0;
};

// 事件处理
const handleSend = (content: string, attachments?: any[]) => {
  if (!content.trim() && (!attachments || attachments.length === 0)) return;

  inputText.value = "";
  emit("send", content, attachments);

  // 自动滚动到底部
  if (chatSettings.value.autoScroll) {
    nextTick(() => {
      scrollToBottom();
    });
  }
};

const handleQuickQuestion = (question: string) => {
  handleSend(question);
};

const handleRetry = (messageId: string) => {
  chatStore.retryMessage(messageId);
};

const handleCopy = (content: string) => {
  navigator.clipboard.writeText(content).then(() => {
    // TODO: 显示复制成功提示
    console.log("复制成功");
  });
};

const handleDeleteMessage = (messageId: string) => {
  emit("messageDelete", messageId);
};

const handleClearChat = () => {
  if (confirm("确定要清空聊天记录吗？")) {
    emit("clearChat");
  }
};

const handleFileUpload = (files: File[]) => {
  // TODO: 处理文件上传
  console.log("文件上传:", files);
};

const handleVoiceInput = (audioBlob: Blob) => {
  // TODO: 处理语音输入
  console.log("语音输入:", audioBlob);
};

const handleSaveSettings = (settings: ChatSettings) => {
  chatSettings.value = { ...settings };
  emit("settingsChange", settings);
  showSettings.value = false;
};

// 监听消息变化，自动滚动
watch(
  () => messages.value.length,
  () => {
    if (chatSettings.value.autoScroll) {
      nextTick(() => {
        scrollToBottom();
      });
    }
  },
);

// 监听会话变化
watch(
  () => props.sessionId,
  (newSessionId) => {
    if (newSessionId) {
      chatStore.loadSession(newSessionId);
    }
  },
  { immediate: true },
);

// 生命周期
onMounted(() => {
  if (messagesRef.value) {
    messagesRef.value.addEventListener("scroll", checkScrollButton);
  }

  // 初始滚动到底部
  nextTick(() => {
    scrollToBottom(false);
  });
});

onUnmounted(() => {
  if (messagesRef.value) {
    messagesRef.value.removeEventListener("scroll", checkScrollButton);
  }
});

// 公开方法
const sendMessage = (content: string, attachments?: any[]) => {
  handleSend(content, attachments);
};

const clearMessages = () => {
  handleClearChat();
};

const focusInput = () => {
  // TODO: 聚焦输入框
};

defineExpose({
  sendMessage,
  clearMessages,
  focusInput,
  scrollToBottom,
});
</script>

<style scoped>
/* 聊天容器 */
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: var(--bg-color);
  border-radius: 12px;
  overflow: hidden;
}

/* 聊天头部 */
.chat-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  border-bottom: 1px solid var(--border-color);
  background-color: var(--bg-secondary);
}

.chat-header-left {
  display: flex;
  align-items: center;
  flex: 1;
  min-width: 0;
}

.chat-header-right {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 人格信息 */
.chat-persona-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.chat-persona-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  overflow: hidden;
  background-color: var(--bg-tertiary);
  display: flex;
  align-items: center;
  justify-content: center;
}

.persona-avatar-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.persona-avatar-icon {
  color: var(--text-tertiary);
}

.chat-persona-details {
  flex: 1;
  min-width: 0;
}

.persona-name {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--text-primary);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.persona-description {
  margin: 2px 0 0;
  font-size: 12px;
  color: var(--text-secondary);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 消息区域 */
.chat-messages {
  flex: 1;
  overflow-y: auto;
  position: relative;
}

.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.chat-messages::-webkit-scrollbar-track {
  background: var(--bg-secondary);
}

.chat-messages::-webkit-scrollbar-thumb {
  background: var(--border-color);
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb:hover {
  background: var(--border-color-hover);
}

/* 欢迎界面 */
.chat-welcome {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  padding: 40px 20px;
}

.welcome-content {
  text-align: center;
  max-width: 400px;
}

.welcome-icon {
  color: var(--text-tertiary);
  margin-bottom: 16px;
}

.welcome-title {
  margin: 0 0 8px;
  font-size: 20px;
  font-weight: 600;
  color: var(--text-primary);
}

.welcome-description {
  margin: 0 0 24px;
  font-size: 14px;
  color: var(--text-secondary);
  line-height: 1.5;
}

.quick-questions {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  justify-content: center;
}

/* 消息列表 */
.messages-list {
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

/* 正在输入指示器 */
.typing-indicator {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 16px 20px;
  animation: fadeIn 0.3s ease;
}

.typing-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  overflow: hidden;
  background-color: var(--bg-tertiary);
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.typing-avatar-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.typing-avatar-icon {
  color: var(--text-tertiary);
}

.typing-content {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.typing-dots {
  display: flex;
  gap: 4px;
  padding: 8px 12px;
  background-color: var(--bg-secondary);
  border-radius: 12px;
  width: fit-content;
}

.typing-dots .dot {
  width: 6px;
  height: 6px;
  background-color: var(--text-tertiary);
  border-radius: 50%;
  animation: typing-bounce 1.4s ease-in-out infinite both;
}

.typing-dots .dot:nth-child(1) {
  animation-delay: -0.32s;
}
.typing-dots .dot:nth-child(2) {
  animation-delay: -0.16s;
}
.typing-dots .dot:nth-child(3) {
  animation-delay: 0s;
}

@keyframes typing-bounce {
  0%,
  80%,
  100% {
    transform: scale(0.8);
    opacity: 0.5;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

.typing-text {
  font-size: 12px;
  color: var(--text-tertiary);
}

/* 滚动到底部按钮 */
.scroll-to-bottom {
  position: absolute;
  bottom: 20px;
  right: 20px;
  z-index: 10;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.scroll-button-enter-active,
.scroll-button-leave-active {
  transition: all 0.3s ease;
}

.scroll-button-enter-from,
.scroll-button-leave-to {
  opacity: 0;
  transform: translateY(20px);
}

/* 输入区域 */
.chat-input-area {
  padding: 16px 20px 20px;
  border-top: 1px solid var(--border-color);
  background-color: var(--bg-secondary);
}

/* 动画 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 响应式 */
@media (max-width: 768px) {
  .chat-header {
    padding: 12px 16px;
  }

  .chat-persona-info {
    gap: 8px;
  }

  .chat-persona-avatar {
    width: 32px;
    height: 32px;
  }

  .persona-name {
    font-size: 14px;
  }

  .persona-description {
    font-size: 11px;
  }

  .messages-list {
    padding: 16px;
    gap: 12px;
  }

  .chat-input-area {
    padding: 12px 16px 16px;
  }

  .welcome-content {
    padding: 20px;
  }

  .quick-questions {
    flex-direction: column;
    align-items: stretch;
  }
}

@media (max-width: 480px) {
  .chat-header {
    padding: 10px 12px;
  }

  .messages-list {
    padding: 12px;
  }

  .chat-input-area {
    padding: 10px 12px 12px;
  }

  .scroll-to-bottom {
    bottom: 16px;
    right: 16px;
  }
}

/* 暗色主题适配 */
@media (prefers-color-scheme: dark) {
  .scroll-to-bottom {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
  }
}

/* 无障碍支持 */
@media (prefers-reduced-motion: reduce) {
  .typing-dots .dot {
    animation: none;
  }

  .scroll-button-enter-active,
  .scroll-button-leave-active {
    transition: none;
  }

  .chat-messages {
    scroll-behavior: auto;
  }
}
</style>
